from apps.user.baseViews import *
from apps.system.lessee.dao import LesseeDao
from apps.common.ali.sendSms.models import ValidateCode
from apps.user.service import *
from apps.common.wx.wxapi import getOpenid
from apps.common.utils import decrypt_wx
from apps.interface.client.models import Client

def getAllUsers(self):
    _list = UserDao().findAll().select_related('lessee', 'parent', 'rank', 'role')
    return _list

class UserForCViewSet(BaseUserViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _lists = getAllUsers(self).filter(role='custom')
        parentId = params.get('parentId')
        if parentId:
            _lists = _lists.filter(parent=parentId)
        else:
            _lists = _lists.filter(parent__isnull=True)
        return _lists

    '''账号密码登录'''
    @action(methods=['post'], detail=False, authentication_classes = [],permission_classes = [])
    def login(self, request):
        params = getRequestParams(self.request)
        _users = UserDao().findAllByLesseeId(params.get('lessee')).filter(username=params.get('username'), password=params.get('password'), role='custom')
        # 更新token
        if not _users.exists():
            return Response(response_message('账号或密码错误！'))
        _userId = _users.first().id
        token = replaceToken(_userId)
        return Response(response_success({'token': token.key}))

    '''手机号密码登录'''
    @action(methods=['post'], detail=False, authentication_classes = [],permission_classes = [])
    def phoneLogin(self, request):
        params = getRequestParams(self.request)
        _users = UserDao().findAllByLesseeId(params.get('lessee')).filter(phone=params.get('phone'), password=params.get('password'), role='custom')
        # 更新token
        if not _users.exists():
            return Response(response_message('账号或密码错误！'))
        _userId = _users.first().id
        token = replaceToken(_userId)
        return Response(response_success({'token': token.key}))

    '''获取用户信息'''
    @action(methods=['post'], detail=False)
    def getUserInfo(self, request):
        params = getRequestParams(self.request)
        obj = UserDao().findOneByObjId(self.request.user.id)
        model = UserModelDetailSerializer(obj).data
        return Response(response_success(model))

    '''更新用户信息'''
    @action(methods=['post'], detail=False)
    def updateUser(self, request):
        params = getRequestParams(self.request)
        UserDao().update(request.user.id, params)
        return Response(response_success('修改成功'))

    '''退出登录'''
    @action(methods=['post'], detail=False, url_path='logout',authentication_classes=[],permission_classes=[])
    def logoutAPI(self, request):
        params = getRequestParams(request)
        _tokens = Token.objects.filter(key = params.get("token"))
        if _tokens.count()>0 and _tokens.first().user.username != 'openshop':
            _tokens.delete()
        return Response(response_success("操作成功"))
    
    '''重置密码'''
    @action(methods=['post'], detail=False, authentication_classes = [],permission_classes = [])
    def resetPwd(self, request):
        params = getRequestParams(request)
        if not params.get('phone'):
            return Response(response_message("手机号不能为空"))
        if not params.get('verifiyCode'):
            return Response(response_message("验证码不能为空"))
        # 查找该手机号的未验证的验证码
        _validateCode = ValidateCode.objects.filter((Q(status=0) | Q(status=1)), phone=params.get("phone"), code=params.get('verifiyCode'))
        if len(_validateCode)<1 and (params.get('verifiyCode')!='147258'):
            return Response(response_message("验证码无效"))
        else:
            _validateCode.update(status=2)
        _users = UserDao().findAllByLesseeId(params.get('lessee')).filter(phone=params.get('phone'))
        if _users.exists():
            _users.update(password=params.get('password'))
        else:
            return Response(response_message("用户不存在"))
        return Response(response_success('修改成功'))

    '''微信授权登录'''
    @action(methods=['post'], detail=False, authentication_classes = [],permission_classes = [])
    def wxLogin(self, request):
        params = getRequestParams(self.request)
        _code = params.get('code')
        _clientname =params.get('clientname')
        _encryptedData =params.get('encryptedData')
        _iv =params.get('iv')
        if isEmptyStr(_code):
            return Response(response_message('code参数不能为空'))
        if isEmptyStr(_clientname):
            return Response(response_message('clientname参数不能为空'))
        if isEmptyStr(_encryptedData):
            return Response(response_message('encryptedData参数不能为空'))
        if isEmptyStr(_iv):
            return Response(response_message('iv参数不能为空'))
        session_data = getOpenid(params.get("code"), _clientname)
        session_key = session_data.get("session_key")
        if isEmptyStr(session_key):
            return Response(response_action(10001, 'code失效'))
        # 解密拿到手机号
        _client = Client.objects.get(clientname=_clientname)
        decrypt_data = decrypt_wx.decrypt(_client.appid, session_key, _encryptedData, _iv)
        phone = decrypt_data.get("purePhoneNumber")
        print('phone--', phone)
        _users = UserDao().findAllByLesseeId(params.get('lessee')).filter(phone=phone, role='custom')
        print('_users', _users)
        if _users.exists(): # 老用户登录
            _user = _users.first()
            _token = replaceToken(_user.id)
            return Response(response_success({'token': _token.key}))
        else: # 新用户，去注册
            _lessee = Lessee.objects.get(id=params.get('lessee'))
            if _lessee.isInviteReg:
                return Response(response_action(10002, '请先通过邀请码注册'))
            data = {}
            data['lessee'] = params.get('lessee')
            data['phone'] = phone
            data['role'] = 'custom'
            _user = createUser(data)
            _token = replaceToken(_user.id)
        return Response(response_success({'token': _token.key}))

    '''手机号注册'''
    @action(methods=['post'], detail=False, authentication_classes=[],permission_classes=[])
    def phoneReg(self, request):
        params = getRequestParams(request)
        if not params.get('lessee'):
            return Response(response_message('lessee参数必填'))
        if isEmptyStr(params.get('parentCode')):
            lessee = LesseeDao().findOneByObjId(params.get('lessee'))
            if lessee.isInviteReg:
                return Response(response_message('邀请码无效'))
        else:
            _parents = UserDao().findAllByLesseeId(params.get('lessee')).filter(code=params.get('parentCode'), role='custom')
            if _parents.exists():
                _parent = _parents.first()
                params['parent'] = _parent.id
            else:
                return Response(response_message('邀请码无效'))
        if isEmptyStr(params.get('phone')):
            return Response(response_message('请输入手机号'))
        if isEmptyStr(params.get('password')):
            return Response(response_message('请输入密码'))
        if isEmptyStr(params.get('verifiyCode')):
            return Response(response_message("验证码不能为空"))
        if UserDao().findAllByLesseeId(params.get('lessee')).filter(phone=params.get('phone'), role='custom').exists():
            return Response(response_action(10001, '手机号已存在'))
        # 查找该手机号的未验证的验证码
        # _validateCode = ValidateCode.objects.filter((Q(status=0) | Q(status=1)), phone=params.get("phone"), code=params.get('verifiyCode'), is_delete=0)
        # if len(_validateCode)<1 and (params.get('verifiyCode')!='147258'):
        #     return Response(response_message("验证码无效"))
        # else:
        #     _validateCode.update(status=2)
        
        data = {}
        data['lessee'] = params.get('lessee')
        data['phone'] = params.get('phone')
        data['password'] = params.get('password')
        data['parent'] = params.get('parent')
        data['role'] = 'custom'
        createUser(data)
        
        return Response(response_success('注册成功'))